home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-01
/
graycd.zip
/
GRAYCD.C
< prev
Wrap
C/C++ Source or Header
|
1992-01-26
|
3KB
|
126 lines
/* generate Gray code for a bit string NrBits in length
Gray code is a binary numbering system in which successive bit patterns
differ in only one bit. Useful for shaft encoding and other applications
where we might be off a bit (pun intended).
for example, the command:
graycd 3
would generate the following eight lines showing the line number,
along with the decimal and binary values of the Gray code.
1 0 0 0 0 5 6 1 1 0
2 1 0 0 1 6 7 1 1 1
3 3 0 1 1 7 5 1 0 1
4 2 0 1 0 8 4 1 0 0
w.howell (cis 70215,206) 1/24/92
define K_R to compile under BSD4.3 (ie. cc -DK_R graycd.c)
define DEBUG to include Gray code check in bitprint routine
tested under MicroSoft C6.0, Borland C++ 1.0, as well as
under BSD4.3 and SCO UNIX V (an other MicroSoft C).
*/
#include <stdio.h>
#define MAX 14
#ifdef K_R
void main( );
void gray( );
void bitprint( );
void usage( );
#else
void main( int, char * * );
void gray( int );
void bitprint( void );
void usage( void );
#endif
int NrBits, Value = 0;
void main( argc, argv)
int argc;
char **argv;
{
int main_mask;
/* get the command line arg of number of bits */
if(argc < 2) usage();
NrBits = atoi(argv[1]);
if(NrBits < 2 | NrBits > MAX) {
fprintf(stderr,"NrBits = %d outside the range of 2 to %d\n", NrBits, MAX);
usage();
}
/* now let's do it */
main_mask = (1 << (NrBits - 1) );
gray(main_mask);
}
/* recursively print gray code until mask = 0 */
void gray( mask )
int mask;
{
int new_mask;
new_mask = mask >> 1;
if(new_mask) {
gray(new_mask);
Value = Value ^ mask;
gray(new_mask);
}
else {
bitprint();
Value = Value ^ mask;
bitprint();
}
}
#ifdef K_R
void bitprint( )
#else
void bitprint(void)
#endif
{
#ifdef DEBUG
static int last = 1; /* start with 1 because first is 0 */
int test = 0, bitcount = 0;
#endif
static int count = 0;
int i, bit_mask = (1 << (NrBits - 1) );
count++;
printf("%3d %3d ", count, Value);
for(i=0; i<NrBits; i++, bit_mask = bit_mask >> 1) {
if(Value & bit_mask) printf(" 1");
else printf(" 0");
}
printf("\n");
#ifdef DEBUG
/* count the number of bits changed -- BETTER BE ONLY 1 if gray */
test = last ^ Value;
for(; test; test = test >> 1) if(test & 0x0001) bitcount++;
if(bitcount != 1) {
fprintf(stderr,"%d Changes from %d to %d\n", bitcount, last, Value);
usage();
}
last = Value;
#endif
}
#ifdef K_R
void usage()
#else
void usage(void)
#endif
{
fprintf(stderr, "\nUSAGE: graycd nr_bits\n\n");
exit(4);
}